<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="楼栋号" prop="buildingNumber">
        <el-select v-model="queryParams.buildingNumber" placeholder="请选择楼栋号" clearable>
          <el-option v-for="dict in building_number" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in repair_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['repairSys:orders:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['repairSys:orders:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['repairSys:orders:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['repairSys:orders:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="维修订单id" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="楼栋号" align="center" prop="buildingNumber">
        <template #default="scope">
          <dict-tag :options="building_number" :value="scope.row.buildingNumber" />
        </template>
      </el-table-column>
      <el-table-column label="门牌号" align="center" prop="houseNumber" />
      <el-table-column label="预约上门时间" align="center" prop="visitTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.visitTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="故障类型" align="center" prop="repairType">
        <template #default="scope">
          <dict-tag :options="repair_type" :value="scope.row.repairType" />
        </template>
      </el-table-column>
      <el-table-column label="故障图片" align="center" prop="repairImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.repairImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="故障描述" align="center" prop="repairDesc" />
      <el-table-column label="发布时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-text size="large" class="mx-1" type="primary">
            <dict-tag  :options="repair_status" :value="scope.row.status" />
          </el-text>
          
        </template>
      </el-table-column>
      <el-table-column label="分配工作人员姓名" align="center" prop="workerName">
        <template #default="scope">
          <span>{{ scope.row.workerName }}</span>
          <!-- <el-select v-model="form.buildingNumber" placeholder="请选择工作人员" v-else>
            <el-option
              v-for="dict in workerList"
              :key="dict.userId"
              :label="dict.name"
              :value="dict.userId"
            ></el-option>
          </el-select> -->
        </template>
      </el-table-column>
      
      <el-table-column label="开始处理消息" align="center" prop="startInfo" />
      <el-table-column label="开始处理图片" align="center" prop="startImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.startImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="处理完成消息" align="center" prop="finishInfo" />
      <el-table-column label="处理完成图片" align="center" prop="finishImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.finishImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleAllocation(scope.row)"
            v-hasPermi="['repairSys:orders:edit']">分配</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['repairSys:orders:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['repairSys:orders:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 修改工作人员弹窗 -->
    <el-dialog :title="title" v-model="showEditWorker" width="500px" append-to-body @close="()=>(showEditWorker=false,currentRow=null)">
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="工作人员" prop="workerName">
          <el-select v-model="form.workerName" placeholder="请选择工作人员" @change=" workerSelectChange">
            <el-option v-for="dict in workerList" :key="dict.userId" :label="dict.name" :value="dict.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改维修订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="楼栋号" prop="buildingNumber">
          <el-select v-model="form.buildingNumber" placeholder="请选择楼栋号">
            <el-option v-for="dict in building_number" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门牌号" prop="houseNumber">
          <el-input v-model="form.houseNumber" placeholder="请输入门牌号" />
        </el-form-item>

        <el-form-item label="预约上门时间" prop="visitTime">
          <el-date-picker clearable v-model="form.visitTime" type="datetime" value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择预约上门时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="故障类型" prop="repairType">
          <el-select v-model="form.repairType" placeholder="请选择故障类型">
            <el-option v-for="dict in repair_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故障图片" prop="repairImg">
          <image-upload v-model="form.repairImg" />
        </el-form-item>
        <el-form-item label="故障描述" prop="repairDesc">
          <el-input v-model="form.repairDesc" placeholder="请输入故障描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in repair_status" :key="dict.value"
              :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/repairSys/orders";
import { listUsers } from "@/api/repairSys/users";
import { ref } from "vue";
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();
const { building_number, repair_type, repair_status } = proxy.useDict('building_number', 'repair_type', 'repair_status');

const ordersList = ref([]);
const open = ref(false);
const showEditWorker = ref(false)
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    phone: null,
    buildingNumber: null,
    status: null,
    workerName: null,
  },
  rules: {
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "手机号码不能为空", trigger: "blur" }
    ],
    buildingNumber: [
      { required: true, message: "楼栋号不能为空", trigger: "change" }
    ],
    houseNumber: [
      { required: true, message: "门牌号不能为空", trigger: "blur" }
    ],
    visitTime: [
      { required: true, message: "预约上门时间不能为空", trigger: "blur" }
    ],
  }
});

onMounted(() => {
  getUserList()
})

const workerList = ref([])
function getUserList() {
  listUsers().then((res) => {
    if (res.code === 200) {
      workerList.value = res.rows.filter((item) => item.role === 1)
      console.log('workerList', workerList.value);
    } else {
      console.log('sblwl');
    }
  })
}
const currEditId=ref(null)
function handleAllocation(row) {
  showEditWorker.value = true
  currEditId.value= row.id
}
const { queryParams, form, rules } = toRefs(data);
function workerSelectChange(id) {
  // console.log('workerSelectChange', id);
  const idx = workerList.value.findIndex(item => item.userId === id)
  if (idx > -1) {
    form.value.workerUserId = id
    form.value.workerName = workerList.value[idx].name
    form.value.id=currEditId.value
    form.value.status=1
    // console.log(' form.workerUserId ', form.workerUserId ,form.workerName)
  } else {
    console.log('wdnmd');
  }
}



/** 查询维修订单列表 */
function getList() {
  loading.value = true;
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  showEditWorker.value = false;
  reset();
  // currEditId.value=null
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    openid: null,
    userInfo: null,
    name: null,
    phone: null,
    buildingNumber: null,
    houseNumber: null,
    visitTime: null,
    repairType: null,
    repairImg: null,
    repairDesc: null,
    status: null,
    workerUserId: null,
    workerName: null,
    createTime: null,
    startInfo: null,
    startImg: null,
    finishInfo: null,
    finishImg: null
  };
  proxy.resetForm("ordersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加维修订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改维修订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          showEditWorker.value = false;
          getList();
        });
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          showEditWorker.value = false;
          getList();
        });
      }
      // currEditId.value=null
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除维修订单编号为"' + _ids + '"的数据项？').then(function () {
    return delOrders(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('repairSys/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

getList();
</script>
